<?php
/**
 * @filesource modules/block/controllers/IndexController.php
 * @author Tran Van Hoang
 * @abstract : List of actions in order
 *   - new
 *   - view
 *   - edit
 *   - delete
 *   - search
 *   - bulk
 *   - translate
 *   TODO: google maps data points for all the districts, cities -> DB
 */ 
 
class Ads_MasterController extends Clu_Controller_Action_Master
{
	public $m; //model

	public function init()
	{
		$this->m = new ads_Model_Ads();
		parent::init();
	}
	
    public function newAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'create ads') === false)
	    {
    	 	$this->renderError(null,t(68));
            return;
	    }
    	//TODO: if both action_url & body_text are not null, then errors
    	$this->viewParams['form'] = new ads_Form_NewAds();
    	$actionUrl = $this->view->hvnUrl(array('module' => 'ads', 'action'=>'new'), 'nocontroller');
    	$this->viewParams['form']->cluBuild(array('action_url' => $actionUrl));
    	if ($this->_request->isPost() && $this->viewParams['form']->isValid($_POST)) 
        {
        	$data = $this->_request->getParams();
        	try
	    	{
	        	$this->m->insertRaw($data, false);
	    		$this->viewParams['successMessage'] = __('Insert ads successful');
	    	}
	    	catch (Exception $e) 
	    	{
	    	    $this->viewParams['errorMessage'] = __('Cannot insert ads');
	    	}
            $lastInsertId = $this->db->lastInsertId();
        }
    }
    
    public function viewAction()
    {
    	$id = $this->_request->getParam("id");
    	if (!$b = $this->m->findByPrimary($id))
        {
            $this->viewParams['errorMessage'] = __('Cannot find the requested ads');
        }
        $this->viewParams['b'] = $b;
    }
    
	public function editAction()
	{
    	$id = $this->_request->getParam("id");
		$sess = new Zend_Session_Namespace(CLU_NS);	
    	if (!$b = $this->m->getAdsData($id))
        {                
            $this->viewParams['errorMessage'] = __('Cannot find the requested ads');
            return;
        }
		
//		$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'update ads') === false)
	    {
    	 	$this->renderError(null,t(68));
            return;
	    }
	    
        //everything's fine. Continue editing
        $this->viewParams['form'] = new ads_Form_NewAds();
        $actionUrl = $this->view->hvnUrl(array('module' => 'ads', 'action'=>'edit'), 'nocontroller');
    	$this->viewParams['form']->cluBuild(array('action_url' => $actionUrl));
        $this->viewParams['id'] = $id;
        //populate the data with 
		if ($this->_request->isGet())
		{
			$formData = $b->toArray();
			//$positions = explode(':',$formData['positions']);
		    $formData['languages'] = explode(',', $b['languages']);
		    $formData['themes'] = explode(',', $b['themes']);
		    $formData['roles'] = explode(',', $b['roles']);
		    $metadata = unserialize($formData['metadata']);
		    $formData['region'] = $metadata['region'];
		    $formData['weight'] = $metadata['weight'];
		    $formData['template'] = explode(',', $metadata['template']);
            $this->viewParams['form']->populateForm($formData);
		}
        if ($this->_request->isPost() && $this->viewParams['form']->isValid($_POST))
        {	
            if ($this->m->saveRaw($b, $this->viewParams['form']->getValues(), $id, false))
            {
                $this->viewParams['operation'] = __("update ads");
            }
            else 
                $this->viewParams['errorMessage'] = __("Could not update ads to DB");
        }
        else 
        	$this->viewParams['errorMessage'] = __("Input is not valid");
	}
        
    public function deleteAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'delete ads') === false)
	    {
    	 	$this->renderError(null,t(68));
            return;
	    }
	    
    	if (!$id = $this->_request->getParam('id'))
    	{
    		$this->viewParams['errorMessage'] = __('No ads id specified');
        }
        
        if ($this->m->deleteByPrimary(array($id)))
        {
            $this->viewParams['operation'] = __("Delete ads");
        }
		else
		{   
			$this->viewParams['errorMessage'] = __('Could not delete from DB');
		}   
    }	
    
	public function searchAction()
	{
		//unset($_SESSION['paginator']);
    	$data = $this->_request->getParams();
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$this->viewParams['form'] = new ads_Form_Search();
	    $actionUrl = $this->hvnUrl(array('module' => 'ads', 'action'=>'search'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'search', 'action_url' => $actionUrl));

        if (isset($data['cluSearch']) || $this->_request->isPost())
        {
	        //place list + pagination
	       	if (!isset($data['ads_perpage']))
    			$data['ads_perpage'] = 10;
    		if (!isset($data['page']))
    			$data['page'] = 1;
    			
		   	$select = $this->m->search($data);
			$paginator = $this->generatePaginator($select, $data['page'], $data['ads_perpage'], 7, 'Jumping');
			$searchUrl = encode_search_url($data, null, "ads");
			$this->viewParams['searchUrl'] = 
			"http://" . SITE_URL . $this->view->hvnUrl(array('action' => 'search', 'module' => 'ads'),'nocontroller') . "?$searchUrl";
			$this->viewParams['form']->populateForm($data);
        }
        
       //the results
       if(isset($paginator))
       {	
	       	$this->viewParams['paginator'] = $paginator;
	       	$roleList = $this->m->getRoleName($paginator->getCurrentItems());
	       	$this->viewParams['adsList'] = $roleList;
	       	/*
			$t = $this->_request->getParam('page');
			$pageNum  = !empty($t) ? $t : 1; 
			$perPage = isset($data['ads_perpage']) ? $data['ads_perpage']:  $data['search_params']['ads_perpage'];
			$this->viewParams['startIndex'] = $perPage * ($pageNum - 1);
			$this->viewParams['numberOfItems'] = $paginator->getTotalItemCount();
			$this->viewParams['perPage'] = $perPage;
			$this->viewParams['pageNum'] = $pageNum;
			$this->viewParams['numberOfPages'] = ceil($this->viewParams['numberOfItems']/$this->viewParams['perPage']);
			*/  
       }
	}
	
	public function contactUsAction()
	{
		$data = $this->_request->getParams();
		$this->viewParams['form'] = new ads_Form_ContactMail();
	    $actionUrl = $this->view->hvnUrl(array('module' => 'ads', 'action'=>'contact-us'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'contact-us', 'action_url' => $actionUrl));
        if ($this->_request->isPost() && $this->viewParams['form']->isValid($_POST))
        {
			$this->sendContactMail($data);
			$this->viewParams['successMessage'] = t(10);
        }
	}
	
	public function sendContactMail($data)
	{
		$this->viewParams['title'] = $data['title'];
		$this->viewParams['name'] = $data['name'];
		$this->viewParams['address'] = $data['address'];
		$this->viewParams['email'] = $data['email'];
		$this->viewParams['body'] = $data['text'];
		$subject = 'Welcome to herevietnam.vn';
		$contactMail = 'contact@gomevietnam.com';
		$mailBody = "<b> Dear   ".$contactMail."   </b> <br/> " .
				t(13) ."  :". "<b>" . $this->viewParams['title'] . "</b>	<br/>" .
				t(434) . "   :" . $this->viewParams['name'] . "<br/>" .
				t(777) . "   :" . $this->viewParams['address'] . "<br/>" .
				t(470) . "   :" . $this->viewParams['email'] . "<br/>" . 
				t(614) . "   :" . $this->viewParams['body'];
		//$mailBody =  $this->view->render('/modules/ads/views/scripts/commonTheme/commonLang/common/mail_contact_us.phtml');
		$mailer = new Clu_Mail_HvnMailer();
		$mailer->sendContactMail($contactMail, $subject, $mailBody);		
	}
}
?>
